package com.tyc.mb.service;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.tyc.mb.mapper.UserMapper;
import com.tyc.mb.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

/**
 * 布隆过滤器
 *
 * @author tyc
 * @version 1.0
 * @date 2021-11-04 11:42:26
 */
@Service
public class BloomFilterService {

    @Autowired
    private UserService userService;

    private BloomFilter<String> bf = null;


    // todo 优化初始化处理 加载所有数据源信息
    private void initBloomFilter(){
        List<User> users = userService.getAll();
        if(null == users || users.isEmpty()){
            return;
        }
        // 创建布隆过滤器（默认误差3%）
        bf = BloomFilter.create(Funnels.stringFunnel(Charset.forName("UTF-8")), users.size());
        users.stream().forEach(user -> bf.put(user.getName()));
    }

    public boolean userNameExist(String userName){
        if(null == bf){
            initBloomFilter();
        }
        return bf.mightContain(userName);
    }
}
